// 从location.search中获取param
export function getParamFromSearch(search = location.search) {
  if (search === '' || search === '?') return {};
  return search.split('&').reduce((prev, cur, i) => {
    let [key, value] = cur.split('=');
    if (i == 0) key = key.slice(1); // 去掉?号
    prev[key] = value;
    return prev;
  }, {});
};

// 对象转查询参数字符串
export function getSearchFromParam(param = {}) {
  let keys = Object.keys(param);
  return keys.map(key => `${key}=${param[key]}`).join('&');
};

// 移除字符串中所有的空白字符
export function trimAll(str) {
  return str.replace(/\s+/g, '');
}

// 字符串转为手机号码格式
export function toPhoneNum(str) {
  return trimAll(str).replace(/(^\d{3}|\d{4})(?=\d)/g, '$1 ');
};

// 将输入框中的输入格式化为手机号码
export const fmtInputToPhoneNum = function () {
  let oldVal = '';
  return function (input) {
    var i = input.selectionStart;
    (i == 4 || i == 9) && (input.value[i - 1] != ' ') && i++;
    if (/^[\d ]*$/.test(input.value) && input.value.length <= 13) {
      oldVal = input.value = toPhoneNum(input.value);
    } else {
      input.value = oldVal;
    }
    input.selectionStart = input.selectionEnd = i;
  };
}();

// 验证手机号码是否合法
export function testPhoneNum(num) {
  return /^1\d{10}$/.test(num);
};

// 移除一个对象中的undefined
export function removeUndefined(obj) {
  Object.keys(obj).forEach(key => {
    if (obj[key] === undefined) delete obj[key];
  });
  return obj;
};

// 判断一个字符串中的所有字符是否都一样
export function isStringPure(str) {
  return Array.prototype.every.call(str, (v, i, arr) => !i || v == arr[i - 1]);
}
